1 /*
2 * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang.reflect;
27
28 import sun.reflect.ConstructorAccessor;
29 import sun.reflect.Reflection;
30 import sun.reflect.generics.repository.ConstructorRepository;
31 import sun.reflect.generics.factory.CoreReflectionFactory;
32 import sun.reflect.generics.factory.GenericsFactory;
33 import sun.reflect.generics.scope.ConstructorScope;
34 import java.lang.annotation.Annotation;
35 import java.util.Map;
36 import sun.reflect.annotation.AnnotationParser;
37 import java.lang.annotation.AnnotationFormatError;
38 import java.lang.reflect.Modifier;
39
40 /**
41 * {@code Constructor} provides information about, and access to, a single
42 * constructor for a class.
43 *
44 * <p>{@code Constructor} permits widening conversions to occur when matching the
45 * actual parameters to newInstance() with the underlying
46 * constructor's formal parameters, but throws an
47 * {@code IllegalArgumentException} if a narrowing conversion would occur.
48 *
49 * @param <T> the class in which the constructor is declared
50 *
51 * @see Member
52 * @see java.lang.Class
53 * @see java.lang.Class#getConstructors()
54 * @see java.lang.Class#getConstructor(Class[])
55 * @see java.lang.Class#getDeclaredConstructors()
56 *
57 * @author Kenneth Russell
58 * @author Nakul Saraiya
59 */
60 public final
61 class Constructor<T> extends AccessibleObject implements
62 GenericDeclaration,
63 Member {
64
65 private Class<T> clazz;
66 private int slot;
67 private Class<?>[] parameterTypes;
68 private Class<?>[] exceptionTypes;
69 private int modifiers;
70 // Generics and annotations support
71 private transient String signature;
72 // generic info repository; lazily initialized
73 private transient ConstructorRepository genericInfo;
74 private byte[] annotations;
75 private byte[] parameterAnnotations;
76
77 // Generics infrastructure
78 // Accessor for factory
79 private GenericsFactory getFactory() {
80 // create scope and factory
81 return CoreReflectionFactory.make(this, ConstructorScope.make(this));
82 }
83
84 // Accessor for generic info repository
85 private ConstructorRepository getGenericInfo() {
86 // lazily initialize repository if necessary
87 if (genericInfo == null) {
88 // create and cache generic info repository
89 genericInfo =
90 ConstructorRepository.make(getSignature(),
91 getFactory());
92 }
93 return genericInfo; //return cached repository
94 }
95
96 private volatile ConstructorAccessor constructorAccessor;
97 // For sharing of ConstructorAccessors. This branching structure
98 // is currently only two levels deep (i.e., one root Constructor
99 // and potentially many Constructor objects pointing to it.)
100 private Constructor<T> root;
101
102 /**
103 * Package-private constructor used by ReflectAccess to enable
104 * instantiation of these objects in Java code from the java.lang
105 * package via sun.reflect.LangReflectAccess.
106 */
107 Constructor(Class<T> declaringClass,
108 Class<?>[] parameterTypes,
109 Class<?>[] checkedExceptions,
110 int modifiers,
111 int slot,
112 String signature,
113 byte[] annotations,
114 byte[] parameterAnnotations)
115 {
116 this.clazz = declaringClass;
117 this.parameterTypes = parameterTypes;
118 this.exceptionTypes = checkedExceptions;
119 this.modifiers = modifiers;
120 this.slot = slot;
121 this.signature = signature;
122 this.annotations = annotations;
123 this.parameterAnnotations = parameterAnnotations;
124 }
125
126 /**
127 * Package-private routine (exposed to java.lang.Class via
128 * ReflectAccess) which returns a copy of this Constructor. The copy's
129 * "root" field points to this Constructor.
130 */
131 Constructor<T> copy() {
132 // This routine enables sharing of ConstructorAccessor objects
133 // among Constructor objects which refer to the same underlying
134 // method in the VM. (All of this contortion is only necessary
135 // because of the "accessibility" bit in AccessibleObject,
136 // which implicitly requires that new java.lang.reflect
137 // objects be fabricated for each reflective call on Class
138 // objects.)
139 Constructor<T> res = new Constructor<>(clazz,
140 parameterTypes,
141 exceptionTypes, modifiers, slot,
142 signature,
143 annotations,
144 parameterAnnotations);
145 res.root = this;
146 // Might as well eagerly propagate this if already present
147 res.constructorAccessor = constructorAccessor;
148 return res;
149 }
150
151 /**
152 * Returns the {@code Class} object representing the class that declares
153 * the constructor represented by this {@code Constructor} object.
154 */
155 public Class<T> getDeclaringClass() {
156 return clazz;
157 }
158
159 /**
160 * Returns the name of this constructor, as a string. This is
161 * the binary name of the constructor's declaring class.
162 */
163 public String getName() {
164 return getDeclaringClass().getName();
165 }
166
167 /**
168 * Returns the Java language modifiers for the constructor
169 * represented by this {@code Constructor} object, as an integer. The
170 * {@code Modifier} class should be used to decode the modifiers.
171 *
172 * @see Modifier
173 */
174 public int getModifiers() {
175 return modifiers;
176 }
177
178 /**
179 * Returns an array of {@code TypeVariable} objects that represent the
180 * type variables declared by the generic declaration represented by this
181 * {@code GenericDeclaration} object, in declaration order. Returns an
182 * array of length 0 if the underlying generic declaration declares no type
183 * variables.
184 *
185 * @return an array of {@code TypeVariable} objects that represent
186 * the type variables declared by this generic declaration
187 * @throws GenericSignatureFormatError if the generic
188 * signature of this generic declaration does not conform to
189 * the format specified in
190 * <cite>The Java™ Virtual Machine Specification</cite>
191 * @since 1.5
192 */
193 public TypeVariable<Constructor<T>>[] getTypeParameters() {
194 if (getSignature() != null) {
195 return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
196 } else
197 return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
198 }
199
200
201 /**
202 * Returns an array of {@code Class} objects that represent the formal
203 * parameter types, in declaration order, of the constructor
204 * represented by this {@code Constructor} object. Returns an array of
205 * length 0 if the underlying constructor takes no parameters.
206 *
207 * @return the parameter types for the constructor this object
208 * represents
209 */
210 public Class<?>[] getParameterTypes() {
211 return (Class<?>[]) parameterTypes.clone();
212 }
213
214
215 /**
216 * Returns an array of {@code Type} objects that represent the formal
217 * parameter types, in declaration order, of the method represented by
218 * this {@code Constructor} object. Returns an array of length 0 if the
219 * underlying method takes no parameters.
220 *
221 * <p>If a formal parameter type is a parameterized type,
222 * the {@code Type} object returned for it must accurately reflect
223 * the actual type parameters used in the source code.
224 *
225 * <p>If a formal parameter type is a type variable or a parameterized
226 * type, it is created. Otherwise, it is resolved.
227 *
228 * @return an array of {@code Type}s that represent the formal
229 * parameter types of the underlying method, in declaration order
230 * @throws GenericSignatureFormatError
231 * if the generic method signature does not conform to the format
232 * specified in
233 * <cite>The Java™ Virtual Machine Specification</cite>
234 * @throws TypeNotPresentException if any of the parameter
235 * types of the underlying method refers to a non-existent type
236 * declaration
237 * @throws MalformedParameterizedTypeException if any of
238 * the underlying method's parameter types refer to a parameterized
239 * type that cannot be instantiated for any reason
240 * @since 1.5
241 */
242 public Type[] getGenericParameterTypes() {
243 if (getSignature() != null)
244 return getGenericInfo().getParameterTypes();
245 else
246 return getParameterTypes();
247 }
248
249
250 /**
251 * Returns an array of {@code Class} objects that represent the types
252 * of exceptions declared to be thrown by the underlying constructor
253 * represented by this {@code Constructor} object. Returns an array of
254 * length 0 if the constructor declares no exceptions in its {@code throws} clause.
255 *
256 * @return the exception types declared as being thrown by the
257 * constructor this object represents
258 */
259 public Class<?>[] getExceptionTypes() {
260 return (Class<?>[])exceptionTypes.clone();
261 }
262
263
264 /**
265 * Returns an array of {@code Type} objects that represent the
266 * exceptions declared to be thrown by this {@code Constructor} object.
267 * Returns an array of length 0 if the underlying method declares
268 * no exceptions in its {@code throws} clause.
269 *
270 * <p>If an exception type is a type variable or a parameterized
271 * type, it is created. Otherwise, it is resolved.
272 *
273 * @return an array of Types that represent the exception types
274 * thrown by the underlying method
275 * @throws GenericSignatureFormatError
276 * if the generic method signature does not conform to the format
277 * specified in
278 * <cite>The Java™ Virtual Machine Specification</cite>
279 * @throws TypeNotPresentException if the underlying method's
280 * {@code throws} clause refers to a non-existent type declaration
281 * @throws MalformedParameterizedTypeException if
282 * the underlying method's {@code throws} clause refers to a
283 * parameterized type that cannot be instantiated for any reason
284 * @since 1.5
285 */
286 public Type[] getGenericExceptionTypes() {
287 Type[] result;
288 if (getSignature() != null &&
289 ( (result = getGenericInfo().getExceptionTypes()).length > 0 ))
290 return result;
291 else
292 return getExceptionTypes();
293 }
294
295 /**
296 * Compares this {@code Constructor} against the specified object.
297 * Returns true if the objects are the same. Two {@code Constructor} objects are
298 * the same if they were declared by the same class and have the
299 * same formal parameter types.
300 */
301 public boolean equals(Object obj) {
302 if (obj != null && obj instanceof Constructor) {
303 Constructor<?> other = (Constructor<?>)obj;
304 if (getDeclaringClass() == other.getDeclaringClass()) {
305 /* Avoid unnecessary cloning */
306 Class<?>[] params1 = parameterTypes;
307 Class<?>[] params2 = other.parameterTypes;
308 if (params1.length == params2.length) {
309 for (int i = 0; i < params1.length; i++) {
310 if (params1[i] != params2[i])
311 return false;
312 }
313 return true;
314 }
315 }
316 }
317 return false;
318 }
319
320 /**
321 * Returns a hashcode for this {@code Constructor}. The hashcode is
322 * the same as the hashcode for the underlying constructor's
323 * declaring class name.
324 */
325 public int hashCode() {
326 return getDeclaringClass().getName().hashCode();
327 }
328
329 /**
330 * Returns a string describing this {@code Constructor}. The string is
331 * formatted as the constructor access modifiers, if any,
332 * followed by the fully-qualified name of the declaring class,
333 * followed by a parenthesized, comma-separated list of the
334 * constructor's formal parameter types. For example:
335 * <pre>
336 * public java.util.Hashtable(int,float)
337 * </pre>
338 *
339 * <p>The only possible modifiers for constructors are the access
340 * modifiers {@code public}, {@code protected} or
341 * {@code private}. Only one of these may appear, or none if the
342 * constructor has default (package) access.
343 */
344 public String toString() {
345 try {
346 StringBuffer sb = new StringBuffer();
347 int mod = getModifiers() & Modifier.constructorModifiers();
348 if (mod != 0) {
349 sb.append(Modifier.toString(mod) + " ");
350 }
351 sb.append(Field.getTypeName(getDeclaringClass()));
352 sb.append("(");
353 Class<?>[] params = parameterTypes; // avoid clone
354 for (int j = 0; j < params.length; j++) {
355 sb.append(Field.getTypeName(params[j]));
356 if (j < (params.length - 1))
357 sb.append(",");
358 }
359 sb.append(")");
360 Class<?>[] exceptions = exceptionTypes; // avoid clone
361 if (exceptions.length > 0) {
362 sb.append(" throws ");
363 for (int k = 0; k < exceptions.length; k++) {
364 sb.append(exceptions[k].getName());
365 if (k < (exceptions.length - 1))
366 sb.append(",");
367 }
368 }
369 return sb.toString();
370 } catch (Exception e) {
371 return "<" + e + ">";
372 }
373 }
374
375 /**
376 * Returns a string describing this {@code Constructor},
377 * including type parameters. The string is formatted as the
378 * constructor access modifiers, if any, followed by an
379 * angle-bracketed comma separated list of the constructor's type
380 * parameters, if any, followed by the fully-qualified name of the
381 * declaring class, followed by a parenthesized, comma-separated
382 * list of the constructor's generic formal parameter types.
383 *
384 * If this constructor was declared to take a variable number of
385 * arguments, instead of denoting the last parameter as
386 * "<tt><i>Type</i>[]</tt>", it is denoted as
387 * "<tt><i>Type</i>...</tt>".
388 *
389 * A space is used to separate access modifiers from one another
390 * and from the type parameters or return type. If there are no
391 * type parameters, the type parameter list is elided; if the type
392 * parameter list is present, a space separates the list from the
393 * class name. If the constructor is declared to throw
394 * exceptions, the parameter list is followed by a space, followed
395 * by the word "{@code throws}" followed by a
396 * comma-separated list of the thrown exception types.
397 *
398 * <p>The only possible modifiers for constructors are the access
399 * modifiers {@code public}, {@code protected} or
400 * {@code private}. Only one of these may appear, or none if the
401 * constructor has default (package) access.
402 *
403 * @return a string describing this {@code Constructor},
404 * include type parameters
405 *
406 * @since 1.5
407 */
408 public String toGenericString() {
409 try {
410 StringBuilder sb = new StringBuilder();
411 int mod = getModifiers() & Modifier.constructorModifiers();
412 if (mod != 0) {
413 sb.append(Modifier.toString(mod) + " ");
414 }
415 TypeVariable<?>[] typeparms = getTypeParameters();
416 if (typeparms.length > 0) {
417 boolean first = true;
418 sb.append("<");
419 for(TypeVariable<?> typeparm: typeparms) {
420 if (!first)
421 sb.append(",");
422 // Class objects can't occur here; no need to test
423 // and call Class.getName().
424 sb.append(typeparm.toString());
425 first = false;
426 }
427 sb.append("> ");
428 }
429 sb.append(Field.getTypeName(getDeclaringClass()));
430 sb.append("(");
431 Type[] params = getGenericParameterTypes();
432 for (int j = 0; j < params.length; j++) {
433 String param = (params[j] instanceof Class<?>)?
434 Field.getTypeName((Class<?>)params[j]):
435 (params[j].toString());
436 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
437 param = param.replaceFirst("\\[\\]$", "...");
438 sb.append(param);
439 if (j < (params.length - 1))
440 sb.append(",");
441 }
442 sb.append(")");
443 Type[] exceptions = getGenericExceptionTypes();
444 if (exceptions.length > 0) {
445 sb.append(" throws ");
446 for (int k = 0; k < exceptions.length; k++) {
447 sb.append((exceptions[k] instanceof Class)?
448 ((Class<?>)exceptions[k]).getName():
449 exceptions[k].toString());
450 if (k < (exceptions.length - 1))
451 sb.append(",");
452 }
453 }
454 return sb.toString();
455 } catch (Exception e) {
456 return "<" + e + ">";
457 }
458 }
459
460 /**
461 * Uses the constructor represented by this {@code Constructor} object to
462 * create and initialize a new instance of the constructor's
463 * declaring class, with the specified initialization parameters.
464 * Individual parameters are automatically unwrapped to match
465 * primitive formal parameters, and both primitive and reference
466 * parameters are subject to method invocation conversions as necessary.
467 *
468 * <p>If the number of formal parameters required by the underlying constructor
469 * is 0, the supplied {@code initargs} array may be of length 0 or null.
470 *
471 * <p>If the constructor's declaring class is an inner class in a
472 * non-static context, the first argument to the constructor needs
473 * to be the enclosing instance; see section 15.9.3 of
474 * <cite>The Java™ Language Specification</cite>.
475 *
476 * <p>If the required access and argument checks succeed and the
477 * instantiation will proceed, the constructor's declaring class
478 * is initialized if it has not already been initialized.
479 *
480 * <p>If the constructor completes normally, returns the newly
481 * created and initialized instance.
482 *
483 * @param initargs array of objects to be passed as arguments to
484 * the constructor call; values of primitive types are wrapped in
485 * a wrapper object of the appropriate type (e.g. a {@code float}
486 * in a {@link java.lang.Float Float})
487 *
488 * @return a new object created by calling the constructor
489 * this object represents
490 *
491 * @exception IllegalAccessException if this {@code Constructor} object
492 * is enforcing Java language access control and the underlying
493 * constructor is inaccessible.
494 * @exception IllegalArgumentException if the number of actual
495 * and formal parameters differ; if an unwrapping
496 * conversion for primitive arguments fails; or if,
497 * after possible unwrapping, a parameter value
498 * cannot be converted to the corresponding formal
499 * parameter type by a method invocation conversion; if
500 * this constructor pertains to an enum type.
501 * @exception InstantiationException if the class that declares the
502 * underlying constructor represents an abstract class.
503 * @exception InvocationTargetException if the underlying constructor
504 * throws an exception.
505 * @exception ExceptionInInitializerError if the initialization provoked
506 * by this method fails.
507 */
508 public T newInstance(Object ... initargs)
509 throws InstantiationException, IllegalAccessException,
510 IllegalArgumentException, InvocationTargetException
511 {
512 if (!override) {
513 if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
514 Class<?> caller = Reflection.getCallerClass(2);
515
516 checkAccess(caller, clazz, null, modifiers);
517 }
518 }
519 if ((clazz.getModifiers() & Modifier.ENUM) != 0)
520 throw new IllegalArgumentException("Cannot reflectively create enum objects");
521 ConstructorAccessor ca = constructorAccessor; // read volatile
522 if (ca == null) {
523 ca = acquireConstructorAccessor();
524 }
525 return (T) ca.newInstance(initargs);
526 }
527
528 /**
529 * Returns {@code true} if this constructor was declared to take
530 * a variable number of arguments; returns {@code false}
531 * otherwise.
532 *
533 * @return {@code true} if an only if this constructor was declared to
534 * take a variable number of arguments.
535 * @since 1.5
536 */
537 public boolean isVarArgs() {
538 return (getModifiers() & Modifier.VARARGS) != 0;
539 }
540
541 /**
542 * Returns {@code true} if this constructor is a synthetic
543 * constructor; returns {@code false} otherwise.
544 *
545 * @return true if and only if this constructor is a synthetic
546 * constructor as defined by
547 * <cite>The Java™ Language Specification</cite>.
548 * @since 1.5
549 */
550 public boolean isSynthetic() {
551 return Modifier.isSynthetic(getModifiers());
552 }
553
554 // NOTE that there is no synchronization used here. It is correct
555 // (though not efficient) to generate more than one
556 // ConstructorAccessor for a given Constructor. However, avoiding
557 // synchronization will probably make the implementation more
558 // scalable.
559 private ConstructorAccessor acquireConstructorAccessor() {
560 // First check to see if one has been created yet, and take it
561 // if so.
562 ConstructorAccessor tmp = null;
563 if (root != null) tmp = root.getConstructorAccessor();
564 if (tmp != null) {
565 constructorAccessor = tmp;
566 } else {
567 // Otherwise fabricate one and propagate it up to the root
568 tmp = reflectionFactory.newConstructorAccessor(this);
569 setConstructorAccessor(tmp);
570 }
571
572 return tmp;
573 }
574
575 // Returns ConstructorAccessor for this Constructor object, not
576 // looking up the chain to the root
577 ConstructorAccessor getConstructorAccessor() {
578 return constructorAccessor;
579 }
580
581 // Sets the ConstructorAccessor for this Constructor object and
582 // (recursively) its root
583 void setConstructorAccessor(ConstructorAccessor accessor) {
584 constructorAccessor = accessor;
585 // Propagate up
586 if (root != null) {
587 root.setConstructorAccessor(accessor);
588 }
589 }
590
591 int getSlot() {
592 return slot;
593 }
594
595 String getSignature() {
596 return signature;
597 }
598
599 byte[] getRawAnnotations() {
600 return annotations;
601 }
602
603 byte[] getRawParameterAnnotations() {
604 return parameterAnnotations;
605 }
606
607 /**
608 * @throws NullPointerException {@inheritDoc}
609 * @since 1.5
610 */
611 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
612 if (annotationClass == null)
613 throw new NullPointerException();
614
615 return (T) declaredAnnotations().get(annotationClass);
616 }
617
618 /**
619 * @since 1.5
620 */
621 public Annotation[] getDeclaredAnnotations() {
622 return AnnotationParser.toArray(declaredAnnotations());
623 }
624
625 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
626
627 private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
628 if (declaredAnnotations == null) {
629 declaredAnnotations = AnnotationParser.parseAnnotations(
630 annotations, sun.misc.SharedSecrets.getJavaLangAccess().
631 getConstantPool(getDeclaringClass()),
632 getDeclaringClass());
633 }
634 return declaredAnnotations;
635 }
636
637 /**
638 * Returns an array of arrays that represent the annotations on the formal
639 * parameters, in declaration order, of the method represented by
640 * this {@code Constructor} object. (Returns an array of length zero if the
641 * underlying method is parameterless. If the method has one or more
642 * parameters, a nested array of length zero is returned for each parameter
643 * with no annotations.) The annotation objects contained in the returned
644 * arrays are serializable. The caller of this method is free to modify
645 * the returned arrays; it will have no effect on the arrays returned to
646 * other callers.
647 *
648 * @return an array of arrays that represent the annotations on the formal
649 * parameters, in declaration order, of the method represented by this
650 * Constructor object
651 * @since 1.5
652 */
653 public Annotation[][] getParameterAnnotations() {
654 int numParameters = parameterTypes.length;
655 if (parameterAnnotations == null)
656 return new Annotation[numParameters][0];
657
658 Annotation[][] result = AnnotationParser.parseParameterAnnotations(
659 parameterAnnotations,
660 sun.misc.SharedSecrets.getJavaLangAccess().
661 getConstantPool(getDeclaringClass()),
662 getDeclaringClass());
663 if (result.length != numParameters) {
664 Class<?> declaringClass = getDeclaringClass();
665 if (declaringClass.isEnum() ||
666 declaringClass.isAnonymousClass() ||
667 declaringClass.isLocalClass() )
668 ; // Can't do reliable parameter counting
669 else {
670 if (!declaringClass.isMemberClass() || // top-level
671 // Check for the enclosing instance parameter for
672 // non-static member classes
673 (declaringClass.isMemberClass() &&
674 ((declaringClass.getModifiers() & Modifier.STATIC) == 0) &&
675 result.length + 1 != numParameters) ) {
676 throw new AnnotationFormatError(
677 "Parameter annotations don't match number of parameters");
678 }
679 }
680 }
681 return result;
682 }
683 }